package com.imooc.distributedemo.common;

import org.springframework.boot.autoconfigure.cache.CacheProperties.Redis;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.core.types.Expiration;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class RedisLock implements AutoCloseable{

    private RedisTemplate redisTemplate;

    private String key ;
    private String value;
    private int expireTime;

    public RedisLock(RedisTemplate redisTemplate,String key,int expireTime){
        this.redisTemplate = redisTemplate;
        this.key = key;
        this.expireTime = expireTime;
        this.value = UUID.randomUUID().toString();
    }

    public boolean getLock(){
        RedisCallback<Boolean> redisCallback = conn->{
            // 设置NX
            RedisStringCommands.SetOption setOption = RedisStringCommands.SetOption.ifAbsent();
            // 设置过期时间
            Expiration expiration = Expiration.seconds(expireTime);

            // 序列化
            byte[] redisKey = redisTemplate.getKeySerializer().serialize(key);
            byte[] redisValue = redisTemplate.getKeySerializer().serialize(value);

            boolean result = conn.set(redisKey,redisValue,expiration,setOption);
            return result;

        };


        Boolean lock = (Boolean)redisTemplate.execute(redisCallback);
        return lock;
    }

    public boolean unlock(){
        String script = " if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                " return redis.call(\"del\", KEYS [1] )\n" +
                " else\n"+
                " return 0\n" +
                "end ";
        List keys = Arrays.asList(key);
        RedisScript<Boolean> redisScript = RedisScript.of(script,Boolean.class);
        Boolean result = (Boolean)redisTemplate.execute(redisScript,keys,value);
        return result;
    }

    @Override
    public void close() throws Exception {
        unlock();
    }
}
